﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Truron.Purchase.Interface;
using Truron.Purchase.Api.Utility;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Truron.Purchase.Model;
using Newtonsoft.Json;
using Truron.Purchase.Utility;
using Newtonsoft.Json.Linq;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service;
using System.Security.Cryptography.X509Certificates;
using Castle.DynamicProxy.Generators.Emitters;
using Microsoft.AspNetCore.Identity;

namespace Truron.Purchase.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class Purchase_OuterRequestController : ControllerBase
    {
        private readonly IPurchase_OuterRequestService _purchase_OuterRequestService;
        private readonly IFlowInstanceService _flowInstanceService;
        private readonly IPurchase_OuterRequestApprovalService _purchase_OuterRequestApprovalService;
        private readonly IPurchase_OuterRequestDetailService _purchase_OuterRequestDetailService;
        private readonly IPurchase_OuterRequestNoteRelationService _purchase_OuterRequestNoteRelationService;
        private readonly IPurchase_OuterRequestDetailApprovalService _purchase_OuterRequestDetailApprovalService;
        private readonly IPurchase_OuterNoteService _Purchase_OuterNoteService;
        private readonly IPurchase_OuterNoteApprovalService _purchase_OuterNoteApprovalService;
        private readonly IPurchase_OuterNoteDetailService _Purchase_OuterNoteDetailService;
        public Purchase_OuterRequestController(IPurchase_OuterRequestService Purchase_OuterRequestService, IFlowInstanceService FlowInstanceService, 
            IPurchase_OuterRequestApprovalService Purchase_OuterRequestApprovalService, IPurchase_OuterRequestDetailService Purchase_OuterRequestDetailService,
            IPurchase_OuterRequestNoteRelationService Purchase_OuterRequestNoteRelationService, IPurchase_OuterRequestDetailApprovalService Purchase_OuterRequestDetailApprovalService,
            IPurchase_OuterNoteService Purchase_OuterNoteService, IPurchase_OuterNoteApprovalService Purchase_OuterNoteApprovalService, IPurchase_OuterNoteDetailService Purchase_OuterNoteDetailService)
        {
            _purchase_OuterRequestService = Purchase_OuterRequestService;
            _flowInstanceService = FlowInstanceService;
            _purchase_OuterRequestApprovalService = Purchase_OuterRequestApprovalService;
            _purchase_OuterRequestDetailService = Purchase_OuterRequestDetailService;
            _purchase_OuterRequestNoteRelationService = Purchase_OuterRequestNoteRelationService;
            _purchase_OuterRequestDetailApprovalService = Purchase_OuterRequestDetailApprovalService;
            _Purchase_OuterNoteService = Purchase_OuterNoteService;
            _purchase_OuterNoteApprovalService = Purchase_OuterNoteApprovalService;
            _Purchase_OuterNoteDetailService = Purchase_OuterNoteDetailService;
        }
        [HttpPost]
        public IActionResult GetList(LayPageModel param)
        {

            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            int pageSize = Convert.ToInt32(param.limit), pageIndex = Convert.ToInt32(param.page);
            var noteTuple = _purchase_OuterRequestService.GetList(param.searchKey, pageSize, pageIndex,param.searchJson);
            var detailList = _purchase_OuterRequestDetailService.GetAllList();
            detailList = detailList.FindAll(t => noteTuple.list.Select(x => x.Id).ToList().Contains(t.RequestId));



            if (noteTuple.count > 0)
            {
                var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, detailList.Select(x => x.Id).ToList());

                foreach(var entity in otherTuple.list)
                {
                    entity.RqeustId = detailList.Find(x => x.Id == entity.NoticeId).RequestId;
                }

                if (otherTuple.code > 0)
                {
                    return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
                }
                foreach (var entity in noteTuple.list)
                {
                    entity.UnitCode = otherTuple.list.Find(x => x.RqeustId == entity.Id) == null ? "" : otherTuple.list.Find(x => x.RqeustId == entity.Id).UnitCode;
                    entity.UnitPrice = otherTuple.list.Find(x => x.RqeustId == entity.Id) == null ? 0 : otherTuple.list.Find(x => x.RqeustId == entity.Id).UnitPrice;
                    entity.UnitScope = otherTuple.list.Find(x => x.RqeustId == entity.Id) == null ? "" : otherTuple.list.Find(x => x.RqeustId == entity.Id).UnitScope;
                    entity.UnitNumber = otherTuple.list.Find(x => x.RqeustId == entity.Id) == null ? 0 : otherTuple.list.Find(x => x.RqeustId == entity.Id).UnitNumber;
                    entity.OrderName = otherTuple.list.Find(x => x.RqeustId == entity.Id) == null ? "" : otherTuple.list.Find(x => x.RqeustId == entity.Id).OrderName;
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
        }
        [HttpPost]
        public IActionResult Save(DataFromCRMOrder param)
        {
            try
            {
                var userToken = SysCenterServiceHelp.GetUser(HttpContext);
                Purchase_OuterRequest entity = new Purchase_OuterRequest();
                entity.Create(userToken);
                entity.RequestNo=$"C{DateTime.Now.ToString("yyMMddfff")}{new Random(Guid.NewGuid().GetHashCode()).Next(10001, 99999)}";
                entity.OrderId = param.OrderId;
                entity.FlowStatus = 0;
                entity.OrderNo = param.OrderNo;
                int resultCode = _purchase_OuterRequestService.Save(entity, userToken);
                List<BackCrmData> BackList = new List<BackCrmData>();
                foreach (int a in param.UnitIds)
                {
                    Purchase_OuterRequestDetail entityD = new Purchase_OuterRequestDetail();
                    entityD.DetailNo= $"C{DateTime.Now.ToString("yyMMddfff")}{new Random(Guid.NewGuid().GetHashCode()).Next(10001, 99999)}";
                    entityD.Create(userToken);
                    entityD.UnitId = a;
                    entityD.OrderNo = param.OrderNo;
                    entityD.RequestId = resultCode;
                    int RequestDId = _purchase_OuterRequestDetailService.save(entityD, userToken);
                    BackCrmData temp=new BackCrmData() { UnitId=a,RequestDId= RequestDId };
                    BackList.Add(temp);
                }
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code=0,data= BackList }));
            }
            catch
            {
                return Ok(JsonConvert.SerializeObject(new ResultData(ErrorCodeConst.ParameterError)));
            }
        }
        public class BackCrmData
        {
            public int UnitId { get; set; }
            public int RequestDId { get; set; }
        }
        [HttpPost]
        public IActionResult Del(RecParam param)
        {
            if (param.strEntity.Length == 0)
                return Ok(JsonConvert.SerializeObject(new ResultData(ErrorCodeConst.ParameterError)));
            List<int> ids = JsonConvert.DeserializeObject<List<int>>(param.strEntity);
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var resultCode = _purchase_OuterRequestService.Del(ids, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData(resultCode)));
        }
        public class DataFromCRMOrder
        {
            public int OrderId { get; set; }
            public List<int> UnitIds { get; set; }
            public string OrderNo { get; set; }
        }
        public class RecParam
        {
            public string strEntity { get; set; }
        }
        public IActionResult CreateFlow(FlowCreateParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            param.UserInfo = userToken;
            _flowInstanceService.CreateFlow(param);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code=0 }));
        }
        public IActionResult AuditFlow(FlowAuditParam param)
        {
            _flowInstanceService.AuditFlow(param);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
        public IActionResult GetFlow(GetFlowInfoParam param)
        {
            var flowInfo = _flowInstanceService.GetFlowInfo(param.BussinessId);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() {data = flowInfo }));
        }
        public class GetListParam
        {
            public int RequestId { get; set; }
        }
        public IActionResult GetDetailList(GetListParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterRequestDetailService.GetDetailList(param.RequestId);
            //var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, new List<int>() { param.RequestId});
            var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, list.Select(x=>x.Id).ToList());
            if (otherTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
            }
            foreach(var entity in list)
            {
                entity.UnitCode = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitCode;
                entity.UnitPrice = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitPrice;
                entity.UnitScope = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitScope;
                entity.UnitNumber = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitNumber;
                entity.OrderNo = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderCode;
                entity.OrderName = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderName;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
        public IActionResult GetQueneeList(LayPageModel param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            int pageSize = Convert.ToInt32(param.limit), pageIndex = Convert.ToInt32(param.page);
            int OuterStatus = -1;
            var agreelist = _purchase_OuterRequestService.GetAgreeList();
            List<int> ownerIds = new List<int>();
            var queryParam = param.searchJson.ToJObject();
            if (queryParam["ownerIds"].IsEmpty())
            {
                ownerIds = userDict.Where(x => x.Value.isSub).Select(x => x.Key).ToList();
            }
            else
            {
                if(queryParam["ownerIds"].ToString().IndexOf('-')>=0)
                {
                    ownerIds.Add(Convert.ToInt32(queryParam["ownerIds"][0].ToString().Split('-')[0]));
                    OuterStatus = Convert.ToInt32(queryParam["ownerIds"][0].ToString().Split('-')[1]);
                }
                else
                {
                    ownerIds.Add(Convert.ToInt32(queryParam["ownerIds"][0].ToString()));
                }
                
            }
            if(ownerIds.Count==0)
            {
                ownerIds.Add(userToken.UserId);
            }
            if (!queryParam["deptId"].IsEmpty())
            {
                var userIdTuple = SysCenterServiceHelp.Instance.GetUserByDept(userToken, (int)queryParam["deptId"]);
                if (userIdTuple.code > 0)
                    return Ok(JsonConvert.SerializeObject(new ResultData<object>(userIdTuple.code)));
                ownerIds = userIdTuple.ids.ToList();
            }
            var noteTuple = _purchase_OuterRequestDetailService.GetList(param.searchKey, pageSize, pageIndex, param.searchJson,agreelist.Select(x=>x.Id).ToList(),ownerIds, OuterStatus);
            if(noteTuple.list.Count==0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
            }
            var intList = noteTuple.list.Select(x => x.Id).Distinct().ToList();
            var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, intList);
            if (otherTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
            }
            List<Purchase_OuterRequestNoteRelation> RelationList = _purchase_OuterRequestNoteRelationService.GetRelationListByRequestIds(noteTuple.list.Select(x => x.Id).Distinct().ToList());
            List<Purchase_OuterNoteDetail> OuterNoteDetailList = _Purchase_OuterNoteDetailService.GetListByIds(RelationList.Select(x => x.OuterNoteId).Distinct().ToList()).ToList();
            List<Purchase_OuterNote> OuterNoteList = _Purchase_OuterNoteService.GetRelationList(OuterNoteDetailList.Select(x=>x.NoteId).Distinct().ToList());
            foreach (var entity in noteTuple.list)
            {
                entity.UnitCode = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitCode;
                entity.UnitPrice = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitPrice;
                entity.UnitScope = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitScope;
                entity.UnitNumber = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitNumber;
                entity.OwnerName = entity.OwnerId==0?"等待分配": (userDict.ContainsKey(entity.OwnerId) ? userDict[entity.OwnerId].RealName : "用户不存在");
                //entity.OuterNum = RelationList.FindAll(x => x.OuterRequestId == entity.Id).Sum(x => x.OuterNum);
                //entity.OrderNo = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderCode;
                entity.OuterNoteNo = RelationList.Find(x => x.OuterRequestId == entity.Id) == null ? "尚未关联" : OuterNoteList.Find(x => x.Id == OuterNoteDetailList.Find(x=>x.Id==RelationList.Find(x => x.OuterRequestId == entity.Id).OuterNoteId).NoteId).Code;
                entity.OuterNoteId = RelationList.Find(x => x.OuterRequestId == entity.Id) == null ? 0 : OuterNoteList.Find(x => x.Id == OuterNoteDetailList.Find(x => x.Id == RelationList.Find(x => x.OuterRequestId == entity.Id).OuterNoteId).NoteId).Id;
                entity.OrderName = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderName;

                if (entity.OuterStatus==-1)
                {
                    entity.Auditor = 296;
                    entity.AuditorName = "张陶会";
                }
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
        }
        public IActionResult GetQueneeAuditList(LayPageModel param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));
            }
            var userList = userTuple.list.FindAll(x => x.isSub == true);
            int pageSize = Convert.ToInt32(param.limit), pageIndex = Convert.ToInt32(param.page);
            var noteTuple = _purchase_OuterRequestDetailService.GetAuditList(param.searchKey, pageSize, pageIndex, param.searchJson, userList.Select(x=>x.UserID).ToList());
            if (noteTuple.list.Count == 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
            }
            var intList = noteTuple.list.Select(x => x.Id).Distinct().ToList();
            var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, intList);
            if (otherTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
            }
            foreach (var entity in noteTuple.list)
            {
                entity.UnitCode = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitCode;
                entity.UnitPrice = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitPrice;
                entity.UnitScope = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitScope;
                entity.UnitNumber = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitNumber;
                entity.OwnerName = userList.Find(x=>x.UserID==entity.CreateUser).RealName;
                //entity.OuterNum = RelationList.FindAll(x => x.OuterRequestId == entity.Id).Sum(x => x.OuterNum);
                //entity.OrderNo = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderCode;
                entity.OrderName = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).OrderName;

                if (entity.OuterStatus == -1)
                {
                    entity.Auditor = 296;
                    entity.AuditorName = "张陶会";
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { data = noteTuple.list, count = noteTuple.count }));
        }
        public IActionResult GetApproveList(GetListParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterRequestApprovalService.GetApproveList(param.RequestId);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }
        public IActionResult SaveApprove(Purchase_OuterRequestApproval entity)
        {
            //Purchase_OuterRequestApproval entity = param.strEntity.ToObject<Purchase_OuterRequestApproval>();
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            int resultCode = _purchase_OuterRequestApprovalService.Save(entity, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = resultCode }));
        }
        public class ReturnStatusParam
        {
            public List<int> RequestDIds { get; set; }
        }
        public IActionResult ReturnFlowStatus(ReturnStatusParam param)
        {
            if(param.RequestDIds.Count==0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData(ErrorCodeConst.ParameterError)));
            }
            var DetailList = _purchase_OuterRequestDetailService.GetRelationRequestList(param.RequestDIds);
            var relationList = _purchase_OuterRequestNoteRelationService.GetRelationListByRequestIds(DetailList.Select(x => x.Id).ToList());
            var relationNoteList = _Purchase_OuterNoteService.GetRelationList(relationList.Select(x => x.OuterNoteId).Distinct().ToList());
            //var RequestList = _purchase_OuterRequestService.GetAllList();
            var approvelist = _purchase_OuterNoteApprovalService.GetApproveListByIds(relationNoteList.Select(x => x.Id).ToList());
            List<ReturnStatusModel> Results = DetailList.Select(x => new ReturnStatusModel 
            { 
                RequestDId = x.Id, 
                FlowStatus = x.OuterStatus, 
                RequestNo= x.DetailNo,
                //AuditorId= x.OuterStatus == 2 ? (approvelist.Find(x => x.NoteId == (relationList.Find(y => y.OuterRequestId == x.Id).OuterNoteId)) == null ? 0 : approvelist.Find(x => x.NoteId == relationList.Find(y => y.OuterRequestId == x.Id).OuterNoteId).Approver):0,
                //NodeName = x.OuterStatus == 2 ? (approvelist.Find(x => x.NoteId == (relationList.Find(y => y.OuterRequestId == x.Id).OuterNoteId)) == null ? "" : approvelist.Find(x => x.NoteId == relationList.Find(y => y.OuterRequestId == x.Id).OuterNoteId).ApproverName):"",
                OuterStatus = x.OuterStatus==2? relationNoteList.Find(z => z.Id == (relationList.Find(y => y.OuterRequestId == x.Id).OuterNoteId)).FlowStatus :-1 ,
                ExpextMoney = x.OuterStatus == 2 ? relationList.Find(y => y.OuterRequestId == x.Id).ExpectMoney :0 ,
                RealMoney = 0

            }).ToList();
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = Results }));
        }
        public class UpdateOwnerParam
        {
            public int userId { get; set; }
            public List<int> requestIds { get; set; }
        }
        public IActionResult UpdateOwner(UpdateOwnerParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            _purchase_OuterRequestDetailService.UpdateOwner(param.userId, param.requestIds, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = "更新成功" }));
        }
        public class SaveRelationParam
        {
            public int NoteId { get; set; }
            public List<RequestModel> RequestList { get; set; }
            public int Type { get; set; } //2表示新增委外，3表示关联已有委外
            //public decimal SinglePrice { get; set; }
            public int outNum { get; set; }
            public int isFinsish { get; set; }
        }
        public class RequestModel
        {
            public int Id { get; set; }
            public int UnitNumber { get; set; }
        }
        public IActionResult SaveRelation(SaveRelationParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            Purchase_OuterNoteDetail DetailEntity = _Purchase_OuterNoteDetailService.GetEntity(param.NoteId);
            foreach (var d in param.RequestList)
            {
                Purchase_OuterRequestNoteRelation entity = new Purchase_OuterRequestNoteRelation();
                //entity.Create(userToken);
                entity.OuterNoteId = param.NoteId;
                entity.OuterRequestId = d.Id;
                entity.OuterNum = param.outNum;
                entity.ExpectMoney = Math.Round(param.outNum * (DetailEntity.PriceNum / DetailEntity.TypeNum),2);
                
                _purchase_OuterRequestNoteRelationService.Save(entity, userToken);
                //if (param.isFinsish == 1)
                //{
                //    _purchase_OuterRequestDetailService.UpdateStatus(d.Id, 2, userToken);
                //}
               
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = "更新成功" }));
        }
        public class GetRelationRequestListParam
        {
            public int NoteId { get; set; }
        }
        public IActionResult GetRelationRequestList(GetRelationRequestListParam param)
        {
            List<Purchase_OuterRequestNoteRelation> RelationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteId(param.NoteId);
            if(RelationList.Count==0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = null }));
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterRequestDetailService.GetRelationRequestList(RelationList.Select(x=>x.OuterRequestId).ToList());
            List<int> MRequestIds = list.Select(x => x.Id).Distinct().ToList();
            var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, MRequestIds);
            if (otherTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
            }
            foreach (var entity in RelationList)
            {
                entity.UnitId = list.Find(x=>x.Id==entity.OuterRequestId).UnitId;
            }
            foreach(var entity in RelationList)
            {
                entity.UnitPrice = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitPrice;
                entity.UnitScope = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitScope;
                entity.UnitNumber = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitNumber;
                entity.UnitCode = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitCode;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = RelationList }));
        }
        public class GetRelationRequestListNewParam
        {
            public int NoteDId { get; set; }
        }
        public IActionResult GetRelationRequestListNew(GetRelationRequestListNewParam param)
        {
            List<Purchase_OuterRequestNoteRelation> RelationList = _purchase_OuterRequestNoteRelationService.GetRelationListByNoteId(param.NoteDId);
            if (RelationList.Count == 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = null }));
            }
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterRequestDetailService.GetRelationRequestList(RelationList.Select(x => x.OuterRequestId).ToList());
            List<int> MRequestIds = list.Select(x => x.Id).Distinct().ToList();
            var otherTuple = CrmServiceHelp.Instance.GetEntrustsByNotice(userToken, MRequestIds);
            if (otherTuple.code > 0)
            {
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(otherTuple.code)));
            }
            foreach (var entity in RelationList)
            {
                entity.UnitId = list.Find(x => x.Id == entity.OuterRequestId).UnitId;
            }
            foreach (var entity in RelationList)
            {
                entity.UnitPrice = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitPrice;
                entity.UnitScope = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitScope;
                entity.UnitNumber = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? 0 : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitNumber;
                entity.UnitCode = otherTuple.list.Find(x => x.UnitId == entity.UnitId) == null ? "" : otherTuple.list.Find(x => x.UnitId == entity.UnitId).UnitCode;
            }
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = RelationList }));
        }

        public IActionResult GetOuterRequestTreeData(GetTreeDataParam param)
        {
            //先获取所有用户
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            //获取所有业务数据
            List<Purchase_OuterRequest> NoteList = _purchase_OuterRequestService.GetAllList();
            //for(int i=0;i<param.OrderList.Count;i++)
            //{
            //    if()
            //}
            List<TreeModel> ResultTree = new List<TreeModel>();
            bool first = true;
            if (param.OrderList[0]=="user")
            {
               
                //用户、状态分组
                foreach(var entity in userTuple.list)
                {
                    if(NoteList.Exists(x=>x.CreateUser==entity.UserID))
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"{entity.EnglishName}({entity.RealName}) {NoteList.Count(x=>x.CreateUser==entity.UserID)}";
                        temp.id = entity.UserID.ToString();
                        temp.field = "user";
                        temp.href = "";
                        if(first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        //0,1,2三种状态
                        int status1Count = NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == (int)OuterRequestStatus.waitapprove);
                        if(status1Count>0)
                        {
                            TreeModel status1 = new TreeModel();
                            status1.title = $"等待审批({status1Count.ToString()})";
                            status1.id = entity.UserID.ToString()+"-0";
                            status1.field = "userstatus";
                            status1.href = "";
                            temp.children.Add(status1);
                        }

                        int status2Count = NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == (int)OuterRequestStatus.agree);
                        if (status2Count > 0)
                        {
                            TreeModel status2 = new TreeModel();
                            status2.title = $"审批通过({status2Count.ToString()})";
                            status2.id = entity.UserID.ToString() + "-1";
                            status2.field = "userstatus";
                            status2.href = "";
                            temp.children.Add(status2);
                        }

                        int status3Count = NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == (int)OuterRequestStatus.reject);
                        if (status3Count > 0)
                        {
                            TreeModel status3 = new TreeModel();
                            status3.title = $"审批不通过({status3Count.ToString()})";
                            status3.id = entity.UserID.ToString() + "-2";
                            status3.field = "userstatus";
                            status3.href = "";
                            temp.children.Add(status3);
                        }
                        ResultTree.Add(temp);
                    }
                }
            }
            else
            {
                //状态、用户分组
                var stutsList = NoteList.Select(x => x.FlowStatus).Distinct().ToList();
                foreach(int i in stutsList)
                {
                    if(i==0)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"等待审批({NoteList.Count(x=>x.FlowStatus==0)})";
                        temp.id = "0";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach(var entity in userTuple.list)
                        {
                            if(NoteList.Exists(x=>x.CreateUser == entity.UserID&& x.FlowStatus == 0))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == 0)})";
                                userTree.id = "0-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                            
                            
                        }

                        ResultTree.Add(temp);
                    }
                    else if(i==1)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"审批通过({NoteList.Count(x => x.FlowStatus == 1)})";
                        temp.id = "1";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userTuple.list)
                        {
                            if (NoteList.Exists(x => x.CreateUser == entity.UserID && x.FlowStatus == 1))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == 1)})";
                                userTree.id = "1-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }
                    else if(i==2)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"审批拒绝({NoteList.Count(x => x.FlowStatus == 2)})";
                        temp.id = "2";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userTuple.list)
                        {
                            if (NoteList.Exists(x => x.CreateUser == entity.UserID && x.FlowStatus == 2))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.CreateUser == entity.UserID && x.FlowStatus == 2)})";
                                userTree.id = "2-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree }));
        }

        public IActionResult GetOuterQueueTreeData(GetTreeDataParam param)
        {

            //var agreelist = _purchase_OuterRequestService.GetAgreeList();

            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));

            var userlist = userTuple.list.FindAll(x => x.isSub);
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            //获取所有业务数据
            List<Purchase_OuterRequestDetail> NoteList = _purchase_OuterRequestDetailService.GetAllList();
            //NoteList = NoteList.FindAll(t => agreelist.Select(x => x.Id).ToList().Contains(t.RequestId));
            //for(int i=0;i<param.OrderList.Count;i++)
            //{
            //    if()
            //}
            List<TreeModel> ResultTree = new List<TreeModel>();
            bool first = true;
            if (param.OrderList[0] == "user")
            {

                //用户、状态分组
                foreach (var entity in userlist)
                {
                    if (NoteList.Exists(x => x.OwnerId == entity.UserID))
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"{entity.EnglishName}({entity.RealName}) {NoteList.Count(x => x.OwnerId == entity.UserID)}";
                        temp.id = entity.UserID.ToString();
                        temp.field = "user";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        //0,1,2,-1四种状态
                        //int status0Count= NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == (int)OuterRequestUnitStatus.waitapprove);
                        //if(status0Count)

                        int status1Count = NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == (int)OuterRequestUnitStatus.waitdeal);
                        if (status1Count > 0)
                        {
                            TreeModel status1 = new TreeModel();
                            status1.title = $"等待处理({status1Count.ToString()})";
                            status1.id = entity.UserID.ToString() + "-0";
                            status1.field = "userstatus";
                            status1.href = "";
                            temp.children.Add(status1);
                        }

                        int status2Count = NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == (int)OuterRequestUnitStatus.deal);
                        if (status2Count > 0)
                        {
                            TreeModel status2 = new TreeModel();
                            status2.title = $"处理中({status2Count.ToString()})";
                            status2.id = entity.UserID.ToString() + "-1";
                            status2.field = "userstatus";
                            status2.href = "";
                            temp.children.Add(status2);
                        }

                        int status3Count = NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == (int)OuterRequestUnitStatus.finish);
                        if (status3Count > 0)
                        {
                            TreeModel status3 = new TreeModel();
                            status3.title = $"全部委外({status3Count.ToString()})";
                            status3.id = entity.UserID.ToString() + "-2";
                            status3.field = "userstatus";
                            status3.href = "";
                            temp.children.Add(status3);
                        }
                        ResultTree.Add(temp);
                    }
                }
            }
            else
            {
                //状态、用户分组
                var stutsList = NoteList.Select(x => x.OuterStatus).OrderBy(x=>x).Distinct().ToList();
                foreach (int i in stutsList)
                {
                    if(i==-1)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"等待审批({NoteList.Count(x => x.OuterStatus == -1)})";
                        temp.id = "-1";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        //foreach (var entity in userlist)
                        //{
                        //    if (NoteList.Exists(x => x.OwnerId == entity.UserID && x.OuterStatus == 0))
                        //    {
                        //        TreeModel userTree = new TreeModel();
                        //        userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == 0)})";
                        //        userTree.id = "-1-" + entity.UserID;
                        //        userTree.field = "statususer";
                        //        userTree.href = "";
                        //        userTree.spread = false;
                        //        userTree.disabled = false;
                        //        temp.children.Add(userTree);
                        //    }
                        //}

                        ResultTree.Add(temp);
                    }
                    else if(i==-2)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"审批拒绝({NoteList.Count(x => x.OuterStatus == -2)})";
                        temp.id = "-2";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                    }
                    else if (i == 0)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"等待处理({NoteList.Count(x => x.OuterStatus == 0)})";
                        temp.id = "0";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == entity.UserID && x.OuterStatus == 0))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.OwnerId == entity.UserID && x.OuterStatus == 0)})";
                                userTree.id = "0-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }


                        }

                        ResultTree.Add(temp);
                    }
                    else if (i == 1)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"处理中({NoteList.Count(x => x.OuterStatus == 1)})";
                        temp.id = "1";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.CreateUser == entity.UserID && x.OuterStatus == 1))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.CreateUser == entity.UserID && x.OuterStatus == 1)})";
                                userTree.id = "1-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }
                    else if (i == 2)
                    {
                        TreeModel temp = new TreeModel();
                        temp.title = $"全部委外({NoteList.Count(x => x.OuterStatus == 2)})";
                        temp.id = "2";
                        temp.field = "status";
                        temp.href = "";
                        if (first)
                        {
                            temp.spread = true;
                        }
                        else
                        {
                            temp.spread = false;
                        }
                        temp.disabled = false;
                        temp.children = new List<TreeModel>();
                        foreach (var entity in userlist)
                        {
                            if (NoteList.Exists(x => x.CreateUser == entity.UserID && x.OuterStatus == 2))
                            {
                                TreeModel userTree = new TreeModel();
                                userTree.title = $"{entity.EnglishName}({entity.RealName})({NoteList.Count(x => x.CreateUser == entity.UserID && x.OuterStatus == 2)})";
                                userTree.id = "2-" + entity.UserID;
                                userTree.field = "statususer";
                                userTree.href = "";
                                userTree.spread = false;
                                userTree.disabled = false;
                                temp.children.Add(userTree);
                            }
                        }
                        ResultTree.Add(temp);
                    }

                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree }));
        }
        public class GetDetailApproveListParam
        {
            public int RequestDId { get; set; }
        }
           
        public IActionResult GetDetailApproveList(GetDetailApproveListParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            var list = _purchase_OuterRequestDetailApprovalService.GetApproveList(param.RequestDId);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = list }));
        }

        public IActionResult SaveDetailApprove(Purchase_OuterRequestDetailApproval entity)
        {
            //Purchase_OuterRequestApproval entity = param.strEntity.ToObject<Purchase_OuterRequestApproval>();
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            entity.ApproverName = userToken.RealName;
            _purchase_OuterRequestDetailService.UpdateStatus(entity.RequestDId, entity.Action == 1 ? 0 : -2, userToken);
            int resultCode = _purchase_OuterRequestDetailApprovalService.Save(entity, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = resultCode }));
        }
        
        public IActionResult GetOuterQueueAuditTreeData(GetTreeDataParam param)
        {
            List<StatusModel> StatusList = new List<StatusModel>() { 
                new StatusModel() { Code = -1,Name= "等待审批" } , 
                new StatusModel() { Code = -2, Name = "审批不通过" },
                new StatusModel() { Code = 0, Name = "等待分配" },
                new StatusModel() { Code = 1, Name = "处理中" },
                new StatusModel() { Code = 2, Name = "已完成" }
            };
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));

            var userlist = userTuple.list.FindAll(x => x.isSub);
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            List<Purchase_OuterRequestDetail> NoteList = _purchase_OuterRequestDetailService.GetAllList();

            List<TreeModel> ResultTree = new List<TreeModel>();

            if (param.OrderList.Count>=1)
            {
                if(param.OrderList[0]=="user")
                {
                    foreach (var entity in userlist)
                    {
                        if (NoteList.Exists(x => x.CreateUser == entity.UserID))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{entity.EnglishName}({entity.RealName})<font color='red'> {NoteList.Count(x => x.CreateUser == entity.UserID)}</font>";
                            temp.id = entity.UserID.ToString();
                            temp.field = "user";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();


                            
                            ResultTree.Add(temp);
                        }
                    }
                }
                else if(param.OrderList[0] == "status")
                {
                    foreach(var status in StatusList)
                    {
                        if (NoteList.Exists(x => x.OuterStatus == status.Code))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{status.Name} <font color='red'>{NoteList.Count(x => x.OuterStatus == status.Code)}</font>";
                            temp.id = status.Code.ToString();
                            temp.field = "status";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();



                            ResultTree.Add(temp);
                        }
                    }
                }
            }
            if(param.OrderList.Count>=2)
            {
                if(param.OrderList[1]=="status")
                {
                    foreach(var entity in ResultTree)
                    {
                        foreach(StatusModel status in StatusList)
                        {
                            if (NoteList.Exists(x => x.CreateUser == Convert.ToInt32(entity.id) && x.OuterStatus == status.Code))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{status.Name}<font color='red'> {NoteList.Count(x => x.CreateUser == Convert.ToInt32(entity.id) && x.OuterStatus == status.Code)}</font>";
                                temp.id = entity.id+","+status.Code.ToString();
                                temp.field = "userstatus";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
                else if(param.OrderList[1] == "user")
                {
                    foreach (var entity in ResultTree)
                    {
                        foreach (var user in userlist)
                        {
                            if (NoteList.Exists(x => x.CreateUser == user.UserID && x.OuterStatus == Convert.ToInt32(entity.id)))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{user.EnglishName}({user.RealName})<font color='red'> {NoteList.Count(x => x.CreateUser == user.UserID && x.OuterStatus == Convert.ToInt32(entity.id))}</font>";
                                temp.id = entity.id + "," + user.UserID.ToString();
                                temp.field = "statususer";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
            }

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree }));
        }
        public IActionResult GetOuterQueueTreeDataNew(GetTreeDataParam param)
        {
            List<StatusModel> StatusList = new List<StatusModel>() {
                new StatusModel() { Code = 1, Name = "处理中" },
                new StatusModel() { Code = 2, Name = "已完成" }
            };

            var userToken = SysCenterServiceHelp.GetUser(HttpContext);

            var userTuple = SysCenterServiceHelp.Instance.GetUserAllByPower(userToken);//获取所有用户信息(带权限)
            if (userTuple.code > 0)
                return Ok(JsonConvert.SerializeObject(new ResultData<object>(userTuple.code)));

            var userlist = userTuple.list.FindAll(x => x.isSub);
            var userDict = userTuple.list.ToDictionary(x => x.UserID);
            List<Purchase_OuterRequestDetail> NoteList = _purchase_OuterRequestDetailService.GetAllList();
            NoteList = NoteList.FindAll(x => x.OuterStatus >= 0&&(userlist.Select(x=>x.UserID).Contains(x.OwnerId)||x.OwnerId==0));

            List<TreeModel> ResultTree = new List<TreeModel>();

            if (param.OrderList.Count >= 1)
            {
                if (param.OrderList[0] == "user")
                {
                    foreach (var entity in userlist)
                    {
                        if (NoteList.Exists(x => x.OwnerId == entity.UserID))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{entity.EnglishName}({entity.RealName})<font color='red'> {NoteList.Count(x => x.OwnerId == entity.UserID)}</font>";
                            temp.id = entity.UserID.ToString();
                            temp.field = "user";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();



                            ResultTree.Add(temp);
                        }
                    }
                }
                else if (param.OrderList[0] == "status")
                {
                    foreach (var status in StatusList)
                    {
                        if (NoteList.Exists(x => x.OuterStatus == status.Code))
                        {
                            TreeModel temp = new TreeModel();
                            temp.title = $"{status.Name} <font color='red'>{NoteList.Count(x => x.OuterStatus == status.Code)}</font>";
                            temp.id = status.Code.ToString();
                            temp.field = "status";
                            temp.href = "";
                            temp.spread = true;
                            temp.disabled = false;
                            temp.children = new List<TreeModel>();



                            ResultTree.Add(temp);
                        }
                    }
                }
            }
            if (param.OrderList.Count >= 2)
            {
                if (param.OrderList[1] == "status")
                {
                    foreach (var entity in ResultTree)
                    {
                        foreach (StatusModel status in StatusList)
                        {
                            if (NoteList.Exists(x => x.OwnerId == Convert.ToInt32(entity.id) && x.OuterStatus == status.Code))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{status.Name}<font color='red'> {NoteList.Count(x => x.OwnerId == Convert.ToInt32(entity.id) && x.OuterStatus == status.Code)}</font>";
                                temp.id = entity.id + "-" + status.Code.ToString();
                                temp.field = "userstatus";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
                else if (param.OrderList[1] == "user")
                {
                    foreach (var entity in ResultTree)
                    {
                        foreach (var user in userlist)
                        {
                            if (NoteList.Exists(x => x.OwnerId == user.UserID && x.OuterStatus == Convert.ToInt32(entity.id)))
                            {
                                TreeModel temp = new TreeModel();
                                temp.title = $"{user.EnglishName}({user.RealName})<font color='red'> {NoteList.Count(x => x.OwnerId == user.UserID && x.OuterStatus == Convert.ToInt32(entity.id))}</font>";
                                temp.id = entity.id + "-" + user.UserID.ToString();
                                temp.field = "statususer";
                                temp.href = "";
                                temp.spread = true;
                                temp.disabled = false;
                                temp.children = new List<TreeModel>();
                                entity.children.Add(temp);
                            }
                        }
                    }
                }
            }


            List<TreeModel> ResultTree2 = new List<TreeModel>();
            TreeModel privateTree = new TreeModel();
            privateTree.title = $"已分配队列<font color='red'> {NoteList.Count(x => x.OwnerId!=0)}</font>";
            privateTree.id = "private";
            privateTree.field = "private";
            privateTree.href = "";
            privateTree.spread = true;
            privateTree.disabled = false;
            privateTree.children = ResultTree;

            TreeModel publicTree = new TreeModel();
            publicTree.title = $"未分配队列<font color='red'> {NoteList.Count(x => x.OwnerId == 0)}</font>";
            publicTree.id = "public";
            publicTree.field = "public";
            publicTree.href = "";
            publicTree.spread = true;
            publicTree.disabled = false;
            publicTree.children = new List<TreeModel>();

            ResultTree2.Add(privateTree);
            ResultTree2.Add(publicTree);

            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0, data = ResultTree2 }));
        }
        public class FinishOuterRequestParam
        {
            public int RequestId { get; set; }
        }
        public IActionResult FinishOuterRequest(FinishOuterRequestParam param)
        {
            var userToken = SysCenterServiceHelp.GetUser(HttpContext);
            Purchase_OuterRequestDetail entity = _purchase_OuterRequestDetailService.GetEntity(param.RequestId);
            entity.OuterStatus = (int)OuterRequestUnitStatus.finish;
            _purchase_OuterRequestDetailService.save(entity, userToken);
            return Ok(JsonConvert.SerializeObject(new ResultData<object>() { code = 0 }));
        }
    }
}
